//双击关闭app
function keyListen() {
    api.addEventListener({
        name: 'keyback'
    }, function(ret, err) {
        //双击退出
        api.toast({
            msg: '再按一次退出应用',
            duration: 2000,
            location: 'bottom'
        });
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            if (ret) {
                exitApp();
            }
        });
        setTimeout(function() {
            keyListen();
        }, 3000);
    });
}
//关闭app
function exitApp() {
    api.closeWidget({
        id: api.appId,
        retData: {
            name: 'closeWidget'
        },
        animation: {
            type: 'flip',
            subType: 'from_bottom',
            duration: 500
        },
        silent: true
    })
}

//打开UILoading模块加载框
var uiloading, eLoadId;

function showLoading() {
    uiloading = api.require('UILoading');
    uiloading.flower({
        center: {
            marginTop: api.winWidth / 2,
            marginLeft: api.winHeight / 2
        },
        size: 30,
        mask: 'rgba(20,0,0,.2)',
        fixed: true
    }, function(ret) {
        eLoadId = ret.id;
    });
}
// 关闭加载模态框
function hideLoading() {
    if (!uiloading) {
        return
    }
    uiloading.closeFlower({
        id: eLoadId
    });
}

// 弹出框ms弹出提示文字  time弹出时间 不传时默认3000
function toast(msg, time) {
    if (time) {
        api.toast({
            msg: msg,
            duration: time,
            location: 'bottom'
        });
        return;
    }
    api.toast({
        msg: msg,
        duration: 3000,
        location: 'bottom'
    });
}

// 打开frame
function fnReady(Name) {
    headerHeight = document.getElementById('header').offsetHeight;
    api.openFrame({
        name: Name + '_frm',
        url: './' + Name + '_frm.html',
        rect: {
            marginLeft: 0,
            marginTop: headerHeight,
            marginBottom: 0,
            marginRight: 0
        },
        pageParam: api.pageParam,
        reload: true,
        bounces: false,
        bgColor: '#F8F8FE',
        vScrollBarEnabled: false,
        hScrollBarEnabled: false
    })
}

function setStatusBar(color, style) {
    api.setStatusBarStyle({
        color: color,
        style: style
    });
    // 沉浸式状态栏为 header 设置 paddingTop
    $api.fixStatusBar($api.dom('header'));
    $api.fixIos7Bar($api.dom('header'));
    $api.fixTabBar($api.dom('footer'));
}

/**
 * [isDefine 判断值是否定义]
 * @param  {[string]}  value
 * @return {Boolean}
 */
function isDefine(value) {
	if (value == null || value == "" || value == "undefined" || value == undefined
  || value == "null" || value == "(null)" || value == 'NULL' || typeof(value) == 'undefined') {
		return false;
	} else {
		value = value + "";
		value = value.replace(/\s/g, ""); //全局匹配空白字符
		if (value == "") {
			return false;
		}
		return true;
	}
}

/**
 * [openWin 打开新窗口]
 * @param  {[string]} name      [win名称]
 * @param  {[string]} url       [页面地址]
 * @param  {[object]} pageParam [对象参数组]
 */
function openWin(name, url, pageParam) {
	if (isDefine(pageParam)) {
		var pageParam = pageParam;
	} else {
		pageParam = new Object();
	}
	api.openWin({
		name: name,
		url: url,
		pageParam: pageParam
	});
}

// 时间封装
Date.prototype.format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

Date.prototype.popular = function () {
    var thisTime = this.getTime();
    var nowT = new Date();
    var nowTime = nowT.getTime();
    var deltaT = nowTime - thisTime;
    if(0 < deltaT && deltaT < 1000*60*60*24 && this.getDate() == nowT.getDate()){
      return this.getHours() + ":" + (this.getMinutes() < 10?("0"+this.getMinutes()):this.getMinutes());
    }else if(0 < deltaT && deltaT < 1000*60*60*24*2){
      return "昨天 " + this.getHours() + ":" + (this.getMinutes() < 10?("0"+this.getMinutes()):this.getMinutes());
    }else if(0 < deltaT && deltaT < 1000*60*60*24*365){
      return this.format("M月dd日 h:mm")
    }else{
      return this.format("yyyy年M月dd日 h:mm")
    }
};

//执行ajax上传图片
function ajaxUpFile(returnUrl, callback) {
    api.ajax({
        url: "https://api.zetikeji.com/api/storage/file",
        method: 'post',
        data: {
            values: {
                name: '语音/图片/文件'
            },
            files: {
                file: returnUrl
            }
        }
    }, function (ret, err) {
        if(callback){
          callback(ret, err);
        }
    });
}


function playVideo(src){
  var videoPlayer = api.require('videoPlayer');
  videoPlayer.play({
      texts: {
          head: {
              title: ''
          }
      },
      styles: {
          head: {
              bg: 'rgba(0.5,0.5,0.5,0.7)',
              height: 22,
              titleSize: 16,
              titleColor: '#fff',
              backSize: 22,
              backImg: '../../image/chat/icon_back_white.png',
              setSize: 22,
              setImg: '../../image/chat/icon_setting.png'
          },
          foot: {
              bg: 'rgba(0.5,0.5,0.5,0.7)',
              height: 22,
              playSize: 22,
              playImg: '../../image/chat/icon_play.png',
              pauseImg: '../../image/chat/icon_pause.png',
              nextSize: 22,
              nextImg: 'fs://img/back.png',
              timeSize: 14,
              timeColor: '#fff',
              sliderImg: 'fs://img/slder.png',
              progressColor: '#696969',
              progressSelected: '#76EE00',
              lockImg: 'fs://img/slder@2x.png',
              unlockImg: 'fs://img/slder@2x.png',
          }
      },
      path: src, //（可选项）字符串类型；文档的路径，支持网络和本地（fs://）路径；默认：未传值时不播放
      //在 android 平台上不支持 widget://
      autoPlay: true //（可选项）布尔类型；打开时是否自动播放；默认：true（自动播放）
  });
}
